package com.yaorange.module.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yaorange.exception.ValidateException;
import com.yaorange.module.system.repository.SysUserRepository;
import com.yaorange.module.system.service.SysUserRoleService;
import com.yaorange.module.system.service.SysUserService;
import com.yaorange.module.vo.SysUserPageVo;
import com.yaorange.pojo.SysUser;
import com.yaorange.response.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 15332
 * @version 1.0
 * @date 2025/6/16 17:13
 * @description 用户实体业务层
 */
@Service
public class SysUserServiceImpl implements SysUserService {
  @Autowired
  private SysUserRepository repository;

  @Autowired
  private SysUserRoleService service;
  /**
   * 分页条件查询
   * @param userPageVo
   * @return
   */
  @Override
  public PageResult<SysUser> queryByCondition(SysUserPageVo userPageVo) {
//    设置分页参数
    PageHelper.startPage(userPageVo.getPageNum(), userPageVo.getPageSize());
//    接收传回来的数据
    List<SysUser> userList = repository.queryList(userPageVo);
//    构建分页信息对象
    PageInfo pageInfo = new PageInfo<>(userList);
    PageResult<SysUser> build = PageResult.builder().total(pageInfo.getTotal()).data(pageInfo.getList()).build();
    return build;
  }

  /**
   * 根据ID查询
   * @param id
   * @return
   */
  @Override
  public SysUser selectById(Long id) {
    SysUser user = repository.selectList(id);
    return user;
  }

  /**
   * 新增用户
   * @param user
   */
  @Override
  public void insert(SysUser user) {
    repository.insertList(user);
  }

  /**
   * 修改
   * @param id
   * @param user
   */
  @Override
  public void update(SysUser user) {
    if (user.getUserId() == null){
      throw new ValidateException("缺少必要参数，修改失败");
    }
    repository.updateList(user);
  }

  /**
   * 删除
   * @param id
   */
  @Override
  public void delete(Long id) {
    if (id==null){
      throw new ValidateException("缺少重要参数，无法删除");
    }
    repository.deleteList(id);
  }

  /**
   * 为用户分配角色
   * @param id
   * @param roleId
   */
  @Override
  public void grant(Long id, List<Long> roleId) {
    service.addUserRole(id, roleId);
  }

  /**
   * 根据ID显示用户的角色信息
   * @param id
   * @return
   */
  @Override
  public List<Long> select(Long id) {
    List<Long> roleList = service.selectRoleById(id);
    return roleList;
  }

  /**
   * 根据用户名查询用户
   * @param username
   * @return
   */
  @Override
  public SysUser getUserByName(String username) {
    return repository.selectByName(username);
  }
}
